import { forwardRef, useImperativeHandle, useRef, useState } from 'react';
import { Form, Input } from 'antd';
import ModalUtil from '@/utils/modal.js';
import FormModal from '@/components/FormModal/index.jsx';
import { UserApi } from '@/api/user/api.js';

export default forwardRef(function ChangePasswordModal({ onRefresh }, ref) {
  useImperativeHandle(ref, () => ({
    open: (data) => open(data),
    close: () => formRef.current?.close()
  }));

  const [form] = Form.useForm();
  const formRef = useRef(null);
  const [data, setData] = useState();
  const [updateId, setUpdateId] = useState();

  // 打开弹窗
  function open(data) {
    setData(data);
    if (data.userId == null) {
      ModalUtil.error('数据ID丢失，请刷新重试');
      return;
    }
    setUpdateId(data.userId);
    formRef.current?.open();
    form.setFieldsValue(data);
  }

  // 提交表单
  const handleSubmit = async (values) => {
    let isSuccess = false;
    if (values?.password !== values?.confirmPassword) {
      ModalUtil.error('两次密码不一致');
      return;
    }
    const { code } = await UserApi.update(updateId, values);
    if (code === 0) {
      isSuccess = true;
    }
    if (isSuccess) {
      ModalUtil.success('操作成功');
      form?.resetFields();
      onRefresh && onRefresh();
      formRef.current?.close();
    }
  };

  return (
    <>
      <FormModal
        form={form}
        ref={formRef}
        name="userForm"
        title={`修改密码 - ${data?.username}`}
        onFinish={handleSubmit}
        formItems={
          <>
            <Form.Item
              name="password"
              label="新密码"
              rules={[{ required: true, message: '请输入新密码' }]}
            >
              <Input.Password />
            </Form.Item>
            <Form.Item
              name="confirmPassword"
              label="确认密码"
              rules={[{ required: true, message: '请输入确认密码' }]}
            >
              <Input.Password />
            </Form.Item>
          </>
        }
      />
    </>
  );
});
